package com.unisound.tracelog.client.core.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

public final class SpanContext implements Cloneable {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpanContext.class);

    private final Long traceId;
    private final Long spanId;
    private final String name;
    private final Long parentSpanId;

    public SpanContext(Long traceId, Long spanId, String name, Long parentSpanId) {
        this.traceId = traceId;
        this.spanId = spanId;
        this.name = name;
        this.parentSpanId = parentSpanId;
    }

    public Long getTraceId() {
        return traceId;
    }

    public Long getSpanId() {
        return spanId;
    }

    public String getName() {
        return name;
    }

    public Long getParentSpanId() {
        return parentSpanId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        SpanContext that = (SpanContext) o;
        return Objects.equals(traceId, that.traceId) && Objects.equals(spanId, that.spanId) && Objects.equals(name, that.name) && Objects.equals(parentSpanId, that.parentSpanId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(traceId, spanId, name, parentSpanId);
    }

    @Override
    public String toString() {
        return "{"
                + "\"traceId\":"
                + traceId
                + ",\"spanId\":"
                + spanId
                + ",\"name\":\""
                + name + '\"'
                + ",\"parentSpanId\":"
                + parentSpanId
                + "}";
    }

    @Override
    public SpanContext clone() {
        try {
            SpanContext clone = (SpanContext) super.clone();
            return clone;
        } catch (Exception e) {
            LOGGER.error("clone error.", e);
            return null;
        }
    }
}
